import 'dart:io';

import 'package:cave_flutter/common/common_widget.dart';
import 'package:cave_flutter/model/dynamic_model.dart';
import 'package:cave_flutter/style/whl_style.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:dio/dio.dart' as myDio;
import 'package:http_parser/http_parser.dart';

import '../model/image_model.dart';
import '../model/whl_user_info_model.dart';
import '../network/whl_api.dart';
import '../network/whl_network_utils.dart';
import '../routes/whl_app_pages.dart';
import '../utils/imageUtils.dart';
import '../utils/whl_record_voice_utils.dart';
import '../utils/whl_user_utils.dart';

typedef GetUserInfoSuccessCallback = void Function(bool isSuccess);
typedef UploadSuccessCallback = void Function(dynamic value, bool isSuccess);

getUserInfo({bool isLogin = false, GetUserInfoSuccessCallback? callback}) {
  WhlApi.getCurrentUserInfo.get({}).then((value) {
    if (value.isSuccess()) {
      WhlUserInfoModel model = WhlUserInfoModel.fromJson(value.data);
      WhlUserUtils.saveUserInfo(model);
      if (isLogin) {
        if ((model.avatar ?? "").isNotEmpty &&
            (model.nickname ?? "").isNotEmpty &&
            (model.birthDate ?? "").isNotEmpty) {
          WhlUserUtils.setUserInfoComplete(true);
          WhlUserUtils()
              .addAccountToLoc(model, WhlNetWorkUtils.getAccessToken());
          Get.offAllNamed(Routes.main);
        } else {
          Get.toNamed(Routes.completeUserInfo);
        }
      }
      if (callback != null) {
        callback(true);
      }
    } else {
      if (callback != null) {
        callback(false);
      }
    }
  });
}

uploadImageRequest(ImageModel imageModel,
    {UploadSuccessCallback? callBack}) async {
  AssetEntity? entity = imageModel.assetEntity;
  Map<String, dynamic> params = {};
  if (entity != null) {
    final file = await entity?.file;

    String mimeType = entity?.mimeType ?? "";
    params = {
      "path": "image",
      "file": myDio.MultipartFile.fromBytes(
          await compressImageToCustomSize(file?.path ?? ""),
          filename: entity?.title,
          contentType: mimeType.isNotEmpty
              ? MediaType.parse(entity?.mimeType ?? "")
              : MediaType("image", "jpeg")),
    };
  } else {
    File file = File(imageModel.imagePath!);
    params = {
      "path": "image",
      "file": myDio.MultipartFile.fromBytes(
          await compressImageToCustomSize(imageModel.imagePath ?? ""),
          filename: imageModel.name,
          contentType: MediaType("image", "jpeg")),
    };
  }

  ResponseData response = await WhlApi.uploadFile.post(params, isJson: false);
  if (response.isSuccess()) {
    ImageModel model = ImageModel.fromJson(response.data);
    imageModel.imageStatus = 1;
    imageModel.imageUrl = model.imageUrl;
    if (callBack != null) {
      callBack(imageModel, true);
    }
  } else {
    imageModel.imageStatus = -1;
    if (callBack != null) {
      callBack(imageModel, false);
    }
  }
}

uploadVoiceRequest(RecordVoiceModel voiceModel,
    {UploadSuccessCallback? callBack}) async {
  Map<String, dynamic> params = {
    "path": "voice",
    "file": await myDio.MultipartFile.fromFile(voiceModel.path,
        contentType: MediaType("video", "mp4")),
  };

  print('音频参数------------');

  print(params);

  ResponseData response = await WhlApi.uploadFile.post(params, isJson: false);
  if (response.isSuccess()) {
    voiceModel.url = response.data["url"];
    voiceModel.uploadStatus = 1;
    if (callBack != null) {
      callBack(voiceModel, true);
    }
  } else {
    voiceModel.uploadStatus = -1;
    if (callBack != null) {
      callBack(voiceModel, false);
    }
  }
}

dianZanDynamicRequest(
  DynamicModel model, {
  GetUserInfoSuccessCallback? callback,
  DynamicDataSource dataSource = DynamicDataSource.Square,
}) {
  if (model.currentZan == true) {
    return;
  }
  late Future<ResponseData> apiFuture;
  if (dataSource == DynamicDataSource.Cave) {
    apiFuture = WhlApi.caveDianzan.post({"id": model.id});
  } else {
    apiFuture = WhlApi.squareDianzan.post({"id": model.id});
  }
  apiFuture.then((value) {
    if (value.isSuccess()) {
      model.currentZan = true;
      model.goodNum = (model.goodNum ?? 0) + 1;
      if (callback != null) {
        callback(true);
      }
    } else {
      if (callback != null) {
        callback(false);
      }
    }
  });
}

String getSexStringWithValue(int value) {
  String sex = "";
  if (value == 0) {
    sex = "男生";
  } else if (value == 1) {
    sex = "女生";
  } else if (value == 2) {
    sex = "中性";
  } else if (value == 3) {
    sex = "跨性别男性";
  } else if (value == 4) {
    sex = "跨性别女性";
  } else if (value == 5) {
    sex = "偏男两性人";
  } else if (value == 6) {
    sex = "偏女两性人";
  } else if (value == 7) {
    sex = "无性别";
  }
  return sex;
}

String getSexOrgStringWithValue(int value) {
  List sexOrgList = [
    {'text': '主流', 'value': 0},
    {'text': 'les_t', 'value': 1},
    {'text': 'les_f', 'value': 2},
    {'text': 'les_h', 'value': 3},
    {'text': 'gay_btm', 'value': 4},
    {'text': 'gay_tp', 'value': 5},
    {'text': 'gay_vers', 'value': 6},
    {'text': '双性恋', 'value': 7},
    {'text': '泛性恋', 'value': 8},
    {'text': '智性恋', 'value': 9},
    {'text': '颜性恋', 'value': 10},
    {'text': '性单恋', 'value': 11},
    {'text': '半性恋', 'value': 12},
    {'text': '无性恋', 'value': 13},
    {'text': 'Four Love', 'value': 14}
  ];
  String resultText = '';

  for (var i = 0; i < sexOrgList.length; i++) {
    if (sexOrgList[i]['value'] == value) {
      resultText = sexOrgList[i]['text'];
      break;
    }
  }

  if (resultText == '') {
    resultText = '未知';
  }

  return resultText;
}

String getFunRoleStringWithValue(int value) {
  List funRole = [
    {'text': 'sado', 'value': 0},
    {'text': 'maso', 'value': 1},
    {'text': 'dom', 'value': 2},
    {'text': 'sub', 'value': 3},
    {'text': 'switch', 'value': 4},
    {'text': 'cd', 'value': 5}
  ];
  String resultText = '';

  for (var i = 0; i < funRole.length; i++) {
    if (funRole[i]['value'] == value) {
      resultText = funRole[i]['text'];
      break;
    }
  }

  if (resultText == '') {
    resultText = '未知';
  }

  return resultText;
}

/// 获取性别图标
String getGenderIcon(String? gender) {
  String icon = '';
  if (gender == '0' || gender == '3' || gender == '5') {
    icon = 'icon_sex_man_1.png';
  }

  if (gender == '1' || gender == '4' || gender == '6') {
    icon = 'icon_sex_woman_1';
  }

  if (gender == '2' || gender == '7') {
    icon = 'icon_sex_lgbtq_common_0_0';
  }

  return icon;
}

/// 获取性别颜色
Color getGenderColor(String? gender) {
  String color = '';
  if (gender == '0' || gender == '3' || gender == '5') {
    color = '#33A9FF';
  }

  if (gender == '1' || gender == '4' || gender == '6') {
    color = '#FF73A0';
  }

  if (gender == '2' || gender == '7') {
    color = '#000000';
  }
  return kAppColor(color);
}

//            /** vip 1 vip会员,2 svip会员,3 钻石会员 4 黑金会员**/
//  private Integer vip;
//  /** 会员充值类型 1包月会员，2包季会员，3包季会员，4连续包月会员，5连续包季会员，6连续包年会员 **/
//  private Integer rechargeType;
String? getVipIcon(int? vip, int? rechargeType) {
  String? path;
  int vip0 = vip ?? 0;
  if (vip0 > 0) {
    path = 'icon_vip$vip0';
  }
  if (path != null && vip0 < 3 && (rechargeType == 3 || rechargeType == 6)) {
    path = '${path}_3';
  }
  if (path != null) {
    return '$path.png';
  }
  return null;
}
